using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.Filters;

public class AuthFilter : IAsyncActionFilter
{
    public AuthFilter()
    {
    }
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var accountRepository  = context.HttpContext.RequestServices.GetRequiredService<IAccountRepository>();
        if (context.HttpContext.Request.Cookies.TryGetValue("id", out var userId) == false) throw new ForbiddenException("Пользователь не авторизован");
        
        if (long.TryParse(userId ?? "", out var castedUserId) == false) throw new ForbiddenException("Пользователь не авторизован");

        var account = await accountRepository.AsQueryable().FirstOrDefaultAsync(x => x.Id == castedUserId);
        if (account == null) throw new ForbiddenException("Пользователь не авторизован");

        await next.Invoke();
    }
}